<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%@ include file="/wesite/view/common/base.jsp" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport"
          content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <title>提交订单</title>
    <%@ include file="/wesite/view/common/common.jsp" %>
    <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
</head>
<div id="div-order-list" style="display: block; ">
    <div>
        <div class="sure-order marketing-order">
            <div class="sure-order-info">
                <%--<h3><%=WebSession.getWbUser(session).getComname()%></h3>--%>
                <div class="top">
                    <p class="name fl"><i class="ico"></i><span>${address.getuser}</span></p>
                    <p class="phone fr"><i class="ico"></i><span>${address.phone }</span></p>
                </div>
                <div class="cl"></div>
                <div class="addr">
                    <i class="ico"></i>
                    <div class="con fl">
                        <p>${address.shen } ${address.shi } ${address.qu }</p>
                        <p>${address.address }</p>
                    </div>
                </div>
            </div>
            <div class="shopping-cart">
                <a href="javascript:hide_list()">
                <div class="order-list">
                    <ul>
                        <c:forEach items="${products }" var="product">
                            <li><img src="<%=getRandomFileserver()%>${product.photo}"
                                     onerror="this.src='${ctx }/website/images/noimg.jpg'"><span>共${product.buyamount}件</span>
                            </li>
                        </c:forEach>
                    </ul>
                    <div class="dot">
                        <span></span>
                        <span></span>
                        <span></span>
                    </div>
                    <div class="list-count fr">
                        <span>共${totalAmout }件</span>
                    </div>
                </div>
                </a>

                <div class="order-other-info" style="margin: 10px 0;">
                    <ul>
                        <li>
                            <label style="width: 100%;display: block;float: left;">

                                <span class="tit fl" style="color:#333 !important;">货到付款</span>
                                <span class="tit fr"><input style="vertical-align: middle;" name="paytype" type="radio"
                                                            class="aui-radio"
                                                            <c:if test="${ order == null || order.paytype == null || order.paytype eq '2' }">checked="checked"</c:if>
                                                            value="2"></span>
                            </label>
                        </li>
                        <li>
                            <label style="width: 100%;display: block;float: left;">

                                <span class="tit fl" style="color:#333 !important;">微信支付</span>
                                <span class="tit fr"><input style="vertical-align: middle;" name="paytype" type="radio"
                                                            class="aui-radio"
                                                            <c:if test="${ order != null && order.paytype eq '1'}">checked="checked"</c:if>
                                                            value="1"></span>
                            </label>
                        </li>
                    </ul>
                </div>
                <div class="order-other-info">
                    <ul>
                        <%--<li>--%>
                        <%--<span class="tit fl">发票信息：</span>--%>
                        <%--<input class="fr" type="text" value="" readonly="">--%>
                        <%--</li>--%>
                        <li>
                            <span class="tit fl">配送方式：</span>
                            <span style="color:#999;" class="fr">物流配送</span>
                            <%--<input class="fr" type="text" value="物流配送" readonly="">--%>
                            <%--<span class="arrow-r"></span>--%>
                        </li>
                        <li>
                            <span class="tit fl" style="color:#333 !important;">优惠券：</span>
                            <c:choose>
                                <c:when test="${hasCoupon}">
                                    <input class="fr" onclick="selectCoupon()"
                                           <c:if test="${offerMoney > 0}">value="已抵用${offerMoney}元" </c:if>
                                           type="text" value="有可用优惠劵" readonly="">
                                    <span class="arrow-r"></span>
                                </c:when>
                                <c:otherwise>
                                    <span style="color:#999;" class="fr">无可用优惠劵</span>
                                </c:otherwise>
                            </c:choose>
                        </li>
                        <li>
                            <span class="tit fl">备注：</span>
                            <input class="fr" type="text" name="orderbz" value="${order.orderbz}"
                                   placeholder="请输入你对此次交易的备注">
                        </li>
                    </ul>
                </div>
                <div class="summary mt20">
                    <p><label>商品总额</label><span class="fr" name="orderTotalPrice">${order.order_money}</span><span
                            class="fr">¥</span></p>
                    <p><label>促销优惠</label><span class="fr">-¥${order.reduce_money}</span></p>
                    <p><label>优惠券抵扣</label><span class="fr">-¥<c:choose><c:when
                            test="${offerMoney > 0}">${offerMoney}</c:when><c:otherwise>0.00</c:otherwise></c:choose></span>
                    </p>
                </div>
            </div>
        </div>
    </div>
    <div class="h98"></div>
    <div class="sure-order-bottom">
        <div class="fl">
            <p><span>需付款：</span><i>¥${paymoney}</i></p>
        </div>
        <div class="btn fr">
            <a href="javascript:submitorder()" id="but">
                <span class="return">提交订单</span>
            </a>
        </div>
    </div>
</div>
<div style="display: none;padding-bottom: 3rem" id="div-product-list">
    <a class="go-order" href="javascript:show_list();">继续提交订单</a>
    <div class="deliver-list">
        <ul>
            <c:forEach items="${products }" var="product_info">

                <c:if test="${product_info.gift ==0}">
                    <li>
                        <a class="deliver-img" href="${ctx }/we/product/${product_info.productid }"><img
                                src="<%=getRandomFileserver()%>${product_info.photo}"
                                onerror="this.src='${ctx }/website/images/noimg.jpg'"></a>
                        <div class="deliver-text fl">
                            <p class="text-name">${product_info.productname} </p>
                            <p class="text-company txt">${product_info.B_chanjia} </p>
                            <p class="text-st txt">${product_info.B_guige} </p>
                            <p class="text-price">¥${product_info.price} </p>
                            <span class="text-num">X${product_info.buyamount}</span>
                        </div>
                        <div class="cl"></div>
                    </li>
                </c:if>
            </c:forEach>
        </ul>
    </div>
    <div class="deliver-list deliver-order-list">
        <ul>
            <c:forEach items="${products }" var="product_info_zp">
                <c:if test="${product_info_zp.gift ==1 }">
                    <li>
                        <a class="deliver-img" href="${ctx }/we/product/${product_info_zp.productid }"><img
                                src="<%=getRandomFileserver()%>${product_info_zp.photo}"
                                onerror="this.src='${ctx }/website/images/noimg.jpg'"></a>
                        <div class="deliver-text fl">
                            <p class="text-name"><span>赠品</span>${product_info_zp.productname} </p>
                            <p class="text-company txt">${product_info_zp.B_chanjia} </p>
                            <p class="text-st txt">${product_info_zp.B_guige} </p>
                            <p class="text-price">¥0.00 </p>
                            <span class="text-num">X${product_info_zp.buyamount}</span>
                        </div>
                        <div class="cl"></div>
                    </li>
                </c:if>
            </c:forEach>
        </ul>
    </div>
</div>
<input name="code" value="${order.code }" type="hidden">
</body>
<script type="text/javascript" src="${webctx}/script/aui-toast.js"></script>
<script>
    function hide_list() {
        $("#div-order-list").hide();
        $("#div-product-list").show();
    }
    function show_list() {
        $("#div-order-list").show();
        $("#div-product-list").hide();
    }
</script>
<script type="text/javascript">
    apiready = function () {
        api.parseTapmode();
    }
    var toast = new auiToast({});


    function showToastMsg(type, msg) {

        switch (type) {
            case "success":
                toast.success({
                    title: msg,
                    duration: 2000
                });
                break;
            case "fail":
                toast.fail({
                    title: msg,
                    duration: 2000
                });
                break;
            case "info":
                toast.custom({
                    title: msg,
                    html: '<i class="aui-iconfont aui-icon-info"></i>',
                    duration: 2000
                });
                break;
            default:
                break;
        }
    }

    function showToastLoading(msg) {
        toast.loading({
            title: msg
        });
    }

    function hideToastLoading() {
        toast.hide();
    }

    /*添加数量*/
    $(document).ready(function () {
        var reg = /(.*[\:\：]\s*)([\+\d\.]+)(\s*元)/g;
        $(".sy_minus").click(function () {
            var me = $(this), txt = me.next(":text"), pc = me.closest("p");
            var val = parseFloat(txt.val());
            val = val < 1 ? 1 : val;
            txt.val(val - 1);
            var price = parseFloat(pc.prev("p").text().replace(reg, '$2')) * txt.val();
            pc.next("p").text(pc.next("p").text().replace(reg, "$1" + price + "$3"));
            var num = $(this).siblings('input').val();
            $(this).parent().parent().find('.data i.num').html(num)
        });

        $(".sy_plus").click(function () {
            var me = $(this), txt = me.prev(":text"), pc = me.closest("p");
            var val = parseFloat(txt.val());
            txt.val(val + 1);
            var price = parseFloat(pc.prev("p").text().replace(reg, '$2')) * txt.val();
            pc.next("p").text(pc.next("p").text().replace(reg, "$1" + price + "$3"));
            var num = $(this).siblings('input').val();
            $(this).parent().parent().find('.data i.num').html(num)
        });
    })[0].onselectstart = new Function("return false");

    /*全选*/
    $("#allckb").click(function () {
        if (this.checked) {
            $(".selectbox input:checkbox").attr("checked", true);
        } else {
            $(".selectbox input:checkbox").attr("checked", false);
        }
    });

    //选择支付方式
    function selectPayWay() {
        window.location.href = "${ctx}/we/order/availablePayway/" + $("input[type='hidden'][name='code']").val() + "?bz=" + $("[name='orderbz']").val();
    }

    //选择优惠券
    function selectCoupon() {
        window.location.href = "${ctx}/we/coupon/" + $("input[type='hidden'][name='code']").val() + "?ordermoney=" + $("span[name='orderTotalPrice']").text() + "&bz=" + $("[name='orderbz']").val() + "&paytype=" + $('input:radio[name="paytype"]:checked').val();
    }

    function createWxPay(orderSn, payCallback) {
        showToastLoading("发起支付...");
        $.post(apiroot + "/we/pay/create", {"orderType": "PRODUCT_ORDER", "orderSn": orderSn}, function (data1) {
            if (data1.result == "success" && data1.payment.sn) {
                wxPaySn = data1.payment.sn;
                $.post(apiroot + "/we/pay/action", {"payCode": data1.payment.sn}, function (data2) {
                    if (data2.result == "success") {
                        wx.config({
                            debug: false,
                            appId: data2.jsapi.appId,
                            timestamp: data2.jsapi.timestamp,
                            nonceStr: data2.jsapi.nonceStr,
                            signature: data2.jsapi.signature,
                            jsApiList: ['chooseWXPay']
                        });
                        wx.ready(function () {
                            wx.chooseWXPay({
                                timestamp: data2.payinfo.timeStamp,
                                nonceStr: data2.payinfo.nonceStr,
                                package: data2.payinfo.package,
                                signType: data2.payinfo.signType,
                                paySign: data2.payinfo.paySign,
                                success: function (res) {
                                    showToastMsg("success", "支付成功");
                                    payCallback("success");
                                },
                                fail: function (res) {
                                    showToastMsg("fail", "支付失败");
                                    payCallback("fail");
                                },
                                cancel: function (res) {
                                    showToastMsg("info", "支付取消");
                                    payCallback("cancel");
                                }
                            });
                        });
                        wx.error(function (res) {
                            showToastMsg("fail", "微信配置异常");
                            payCallback("failure");
                        });
                    } else {
                        showToastMsg("info", data2.message);
                        payCallback(data2.result);
                    }
                });
            } else {
                showToastMsg("info", data1.message);
                payCallback(data1.result);
            }
        });
    }

    function payCallbackAction(result) {
        hideToastLoading();
        if (wxPaySn) {
            if ("success" == result) {
                window.location.href = apiroot + "/we/pay/result/success?paySn=" + wxPaySn;
            } else {
                window.location.href = apiroot + "/we/pay/result/fail?paySn=" + wxPaySn;
            }
        } else {
            showToastMsg("fail", "未获取到支付单号");
        }
    }

    var wxPaySn = 0;
    var wxPayOrderSn = 0;
    var cashOnDeliveryUrl = "";
    var submiting = false;
    function submitorder() {
        if (wxPayOrderSn != 0) {
            createWxPay(wxPayOrderSn, payCallbackAction);
            return true;
        }
        if (cashOnDeliveryUrl && cashOnDeliveryUrl.trim() != "") {
            window.location.href = cashOnDeliveryUrl.trim();
            return true;
        }
        if (!submiting) {
            submiting = true;
            showToastLoading("正在提交...");
            $("#but").attr("href", "javascript:void(0);");
            setTimeout('$("#but").attr("href","javascript:submitorder()")', 5000);
            $w.httpRequest({
                url: apiroot + "/we/order/submittedOrder/" + $("[name='code']").val(),
                method: "post",
                data: {
                    "paytype": $('input:radio[name="paytype"]:checked').val(),
                    "bz": $("[name='orderbz']").val(),
                },
                ok: function (ret) {
                    var paycode = ret.Data.paycode;
                    if (ret.Data.paytype) {
                        switch (ret.Data.paytype) {
                            case 1://微信支付
                                $("#but span").text("立即支付");
                                $("#but").attr("href", "javascript:createWxPay('" + ret.Data.ordercode + "',payCallbackAction);")
                                createWxPay(ret.Data.ordercode, payCallbackAction);
                                wxPayOrderSn = ret.Data.ordercode;
                                return;
                            case 2://货到付款
                                var url = apiroot + "/we/order/showorderOk/" + ret.Data.ordercode + "/" + ret.Data.paymoney + "/" + ret.Data.paytype;
                                $("#but span").text("货到付款");
                                $("#but").attr("href", url);
                                cashOnDeliveryUrl = url;
                                break;
                            default:
                                //未识别支付方式
                                break;
                        }
                    }
                    window.location.href = apiroot + "/we/order/showorderOk/" + ret.Data.ordercode + "/" + ret.Data.paymoney + "/" + ret.Data.paytype;

                    //if (ret.Data.orderok == 'true') {
                    //    window.location.href = apiroot + "/we/order/showorderOk/" + ret.Data.ordercode + "/" + ret.Data.paymoney + "/" + ret.Data.paytype;
                    //} else {
                    //提交在线支付请求，二期扩展
                    //window.location.href = apiroot + "/we/order/showorderOk/" + ret.Data.ordercode + "/" + ret.Data.paymoney + "/" + ret.Data.paytype;

                    //}
                }, fail: function (ret) {
                    if (ret.MsgCode == '101') {
                        var h = "以下商品库存不足：";
                        var list = window.eval(ret.MsgDesc);
                        for (var i = 0; i < list.length; i++) {
                            h += "\r\n" + (i + 1) + "、" + list[i].productname + (list[i].attrname || '');
                        }
                        new auiToast().fail({
                            title: h,
                            duration: 800
                        });
                    } else if (ret.MsgCode == '102') {
                        var h = "以下商品已下架：";
                        var list = window.eval(ret.MsgDesc);
                        for (var i = 0; i < list.length; i++) {
                            h += "\r\n" + (i + 1) + "、" + list[i].productname + (list[i].attrname || '');
                        }
                        new auiToast().fail({
                            title: h,
                            duration: 800
                        });
                    } else {
                        new auiToast().fail({
                            title: ret.MsgDesc,
                            duration: 800
                        });
                    }
                    return false;
                },
                all: function () {
                    hideToastLoading();
                    submiting = false;
                }
            })
        }
    }
</script>
</html>